package com.marvels.approve.process.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fintech.common.util.JsonUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.marvels.approve.common.service.McamLoanApplyInfoCommonService;
import com.marvels.approve.consum.ApproveConsumerSystemApi;
import com.marvels.approve.consum.ApproveConsumerUmApi;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.process.dao.IFaceSigAppointmentDao;
import com.marvels.approve.process.dao.ILoanApplyCaseDao;
import com.marvels.approve.process.dao.RoomLogDao;
import com.marvels.approve.process.dao.TaskProcessDao;
import com.marvels.approve.process.dto.AssistantDTO;
import com.marvels.approve.process.dto.FaceSigAppointmentDTO;
import com.marvels.approve.process.dto.FaceSigConfigurationDTO;
import com.marvels.approve.process.dto.FaceSignApiDTO;
import com.marvels.approve.process.dto.LoanApplyCaseDTO;
import com.marvels.approve.process.dto.RoomLogDTO;
import com.marvels.approve.process.dto.SysUserDTO;
import com.marvels.approve.process.service.IFaceCheckAssignmentService;
import com.marvels.approve.process.service.IFaceSigAppointmentService;
import com.marvels.approve.process.service.IFaceSigConfigurationService;
import com.marvels.approve.process.service.IFaceSigService;
import com.marvels.common.constants.CaseNodeConstant;
import com.marvels.common.constants.FacesigOperationType;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.constants.PageConstant;
import com.marvels.common.constants.ResponseData;
import com.marvels.common.constants.TencentCloud;
import com.marvels.common.dto.ChannelUserDTO;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.DateUtils;
import com.marvels.common.utils.HttpUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.PageConverter;
import com.marvels.common.utils.ServerProperties;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class FaceSigServiceImpl implements IFaceSigService{

	@Autowired
	private IFaceSigAppointmentService faceSigAppointmentService;
	@Autowired
	private IFaceSigConfigurationService faceSigConfigurationService;
	@Autowired
	private TaskProcessDao taskProcessMapper;
	@Autowired
	private RoomLogDao roomLogMapper;
	@Autowired
	private McamLoanApplyInfoCommonService mcamLoanApplyInfoCommonService;
	@Autowired
	private ApproveConsumerUmApi consumerUmApi;
	@Autowired
	private ApproveConsumerSystemApi consumerSystemApi;
	@Autowired
	private IFaceSigAppointmentDao faceSigAppointmentDao;
	@Autowired
	private IFaceCheckAssignmentService faceCheckAssignmentService;
	@Autowired
	private ILoanApplyCaseDao loanApplyCaseDao;
	@Value("${config.properties.path}")
	private String filePath;
	

	/**
	 * 客户经理获得签名
	 * 
	 * @param token
	 * @return
	 * @throws MarvelsBusinessException 
	 */
	public Map<String, Object> getTencentSig(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("参数对象为空");
		String idFintechUmUser = faceSignApiDto.getIdFintechUmUser();
		Integer appointmentid = faceSignApiDto.getAppointmentid();
		MarvelsLogUtil.getInstance().info("getTencentSig===>>faceSignApiDto:" + faceSignApiDto);
		if (appointmentid != null) {// 不传预约ID的情况为客户经理登录后提前获得腾讯直播相关信息
			try {
				FaceSigAppointmentDTO faceSigAppointment = faceSigAppointmentService.selectByPrimaryKey(appointmentid);
				McamLoanApplyInfoDTO acLoanApplyInfo = taskProcessMapper.selectLoanApplyInfo(faceSigAppointment.getLoanId());
				String time = faceSigAppointment.getCreateTime().getTime() + "";
				// 房间号为预约创建时间戳 秒的后4位加上客户手机号码的后5位
				String roomId = time.substring(6, 10) + acLoanApplyInfo.getMobileNo().substring(6);

				Map<String, Object> requestMap = new HashMap<String, Object>();
				requestMap.put("GroupIdList", new String[] { "" + Integer.valueOf(roomId) });
				String url = null;//QCloudAPI.initAPI(TencentCloud.GET_GROUP_INFO_URL,filePath);
				ResponseData responseData = HttpUtils.http_post_body_json(url, requestMap, null);
				MarvelsLogUtil.getInstance().info("get room Info==>>" + JSONObject.fromObject(responseData));
				if (StringUtils.isEmpty(responseData.getError())) {
					JSONObject respJson= JsonUtil.strConvertJsonObj(responseData.getBody());
					JSONArray jsonArray = (JSONArray) respJson.get("GroupInfo");
					JSONObject roomInfo = (JSONObject) jsonArray.get(0);
					if ("10010".equals(roomInfo.get("ErrorCode").toString()) || "10015".equals(roomInfo.get("ErrorCode").toString())) {
						throw new MarvelsBusinessException("房间未创建!");
					}
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("check room info 检查房间是否已经创建异常!");
				MarvelsLogUtil.getInstance().error("check room info" + e.getMessage());
			}
		}

		String sig = null;//QCloudSigUtils.createSig(idFintechUmUser,filePath);
		boolean sigVerify = false;//QCloudSigUtils.checkSig(sig, idFintechUmUser,filePath);
		MarvelsLogUtil.getInstance().info("签名结果=sig result>>" + sigVerify);
		if (sigVerify == false) {
			throw new MarvelsBusinessException("签名失败!");
		}

		Map<String, Object> loginInfoMap = new HashMap<String, Object>();
		loginInfoMap.put("sdkAppID", TencentCloud.SDKAPPID);
		loginInfoMap.put("appIDAt3rd", TencentCloud.SDKAPPID);
		loginInfoMap.put("identifier", idFintechUmUser);
		loginInfoMap.put("userSig", sig);
		loginInfoMap.put("accountType", TencentCloud.ACCOUNTTYPE);
		return loginInfoMap;
	}

	/**
	 *  预约
	 */
	public String appointment(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("参数对象为空");
		Long date = faceSignApiDto.getDate();
		Integer timeSlotId = faceSignApiDto.getTimeSlotId();
		String loanId =  faceSignApiDto.getLoanId();
		String cid =  faceSignApiDto.getCid();
		Integer id = faceSignApiDto.getUserId();
		String realName = faceSignApiDto.getRealName();
		MarvelsLogUtil.getInstance().info("预约---appointment===>>##realName:" + realName);
		MarvelsLogUtil.getInstance().info("预约---appointment===>>##faceSignApiDto:" + faceSignApiDto);
		MarvelsLogUtil.getInstance().info("预约---appointment===>>##date:" + date);
		MarvelsLogUtil.getInstance().info("预约---appointment===>>##timeSlotId:" + timeSlotId);
		if (date == null || timeSlotId == null || timeSlotId == 0) {
			throw new MarvelsBusinessException("传入预约时间有误!");
		}
		FaceSigConfigurationDTO faceSigTimeConf = faceSigConfigurationService.selectByPrimaryKey(timeSlotId);
		try {
			String dateParam = DateUtils.getDateYYYY_MM_DD(new Date(date));
			String timeParam = DateUtils.getDateHH_MM_SS(faceSigTimeConf.getStartTime());
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (format.parse(dateParam+" "+timeParam).getTime() < new Date().getTime()) {
				throw new MarvelsBusinessException("不可预约已过去的时间!");
			}
		} catch (Exception e2) {
			MarvelsLogUtil.getInstance().error("预约====>>>"+e2);
			throw new MarvelsBusinessException("预约时间异常!",e2);
		}

		//取面签岗对应的人员
		List<SysUserDTO> userList = faceSigAppointmentService.selectFaceSignUsers();
		if(CollectionUtils.isEmpty(userList)){
			throw new MarvelsBusinessException("没有可以面签的人员！");
		}
		Integer canFacesignNumber = userList.size();
		//已经预约的人数
		FaceSigAppointmentDTO faceSignDto = new FaceSigAppointmentDTO();
		faceSignDto.setTimeId(timeSlotId);
		faceSignDto.setAppointmentDate(new Date());
		Integer hasBookNumber = faceSigAppointmentService.queryDateTimeCount(faceSignDto);
		//可调整的人数
		String canAdjustStr = ServerProperties.getValue(filePath, "resource.properties", "facesign.adjust.count");
		Integer canAdjustNumber  = 0;
		if(!StringUtils.isEmpty(canAdjustStr)){
			canAdjustNumber = Integer.parseInt(canAdjustStr);
		}
		//可调整人数
		if(canFacesignNumber-canAdjustNumber<=hasBookNumber){
			throw new MarvelsBusinessException("没有可以预约的坐席了！");
		}
		if (loanId == null) {
			throw new MarvelsBusinessException("无订单ID!");
		}

		McamLoanApplyInfoDTO acLoanApplyInfo = taskProcessMapper.selectLoanApplyInfo(loanId);
		if (acLoanApplyInfo == null) {
			throw new MarvelsBusinessException("loanId为" + loanId + "没有对应的贷款单号");
		}
		//获取现在的面签状态
		Integer count = faceSigAppointmentDao.selectedPassedCount(loanId);
		if(count<=0 && !LoanStateConstant.P01.equals(acLoanApplyInfo.getStatus())){
			throw new MarvelsBusinessException("贷款状态不符合预约状态！");
		}
		if (faceSigAppointmentService.checkRepeartLoanId(loanId) > 0) {
			throw new MarvelsBusinessException("不可重复提交预约!");
		}
		//重新预约的情况，将分配人置空，预约后可以重新取件
		if(count>0){
			LoanApplyCaseDTO caseDto = new LoanApplyCaseDTO();
			caseDto.setLoanId(loanId);
			caseDto.setCurNodeCode(CaseNodeConstant.WOINTERVIEW.getCode());
			loanApplyCaseDao.updateAssignee(caseDto);
		}
		
		ChannelUserDTO currentUser = new ChannelUserDTO();
		currentUser.setRealName(realName);
		currentUser.setId(id);
		currentUser.setCid(cid);
		faceSigAppointmentService.doAppointment(currentUser, acLoanApplyInfo, timeSlotId, new Date(date),null,false);
		return null;
	}

	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	public String cancelAppointment(FaceSignApiDTO faceSignApiDto)throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		Integer appointmentId = faceSignApiDto.getAppointmentid();
		Integer id = faceSignApiDto.getUserId();
		MarvelsLogUtil.getInstance().info("cancelAppointment====>>appointmentId=" + faceSignApiDto);
		if (appointmentId == null) {
			throw new MarvelsBusinessException("预约ID为空");
		}
		FaceSigAppointmentDTO faceSigAppointment = faceSigAppointmentService.selectByPrimaryKey(appointmentId);
		if (faceSigAppointment == null) {
			throw new MarvelsBusinessException("无该预约信息!");
		}
		if(id==null||id==0){
			throw new MarvelsBusinessException("用户ID为空!");
		}
		if (!id.equals(faceSigAppointment.getUserId())) {
			throw new MarvelsBusinessException("非法操作!");
		}
		faceSigAppointment.setCancel(0);
		try {
			if (faceSigAppointmentService.updateAppointment(faceSigAppointment,false) <= 0) {
				throw new MarvelsBusinessException("取消预约失败!");
			}
			int count = mcamLoanApplyInfoCommonService.updateMcamLoanApplyInfoStatusByLoanId(faceSigAppointment.getLoanId(), LoanStateConstant.P01, null, MarvelsConstant.USER);
			if (count < 1) {// 视频面签已预约
				throw new MarvelsBusinessException("取消预约失败!");
			}
			//修改case表，将assignee置空
			LoanApplyCaseDTO loanApplyCase=new LoanApplyCaseDTO();
			loanApplyCase.setLoanId(faceSigAppointment.getLoanId());
			loanApplyCase.setCurNodeCode(CaseNodeConstant.WOINTERVIEW.getCode());
			loanApplyCaseDao.updateAssignee(loanApplyCase);
			
			MarvelsLogUtil.getInstance().info("cancelAppointment====>>成功取消预约=" + faceSignApiDto);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("cancelAppointment_excep", e);
			throw new MarvelsBusinessException("取消预约失败!");
		}
		return null;
	}

	/**
	 * 推送视频面签(开始视频面签)
	 * 
	 * @param appointmentId
	 * @return
	 * @throws MarvelsBusinessException 
	 */
	public String pushFaceSig(FaceSigAppointmentDTO dto) throws MarvelsBusinessException {
		String jsonResult = new String();
		if (dto == null) {
			throw new MarvelsBusinessException("无预约ID");
		}
		try {
			FaceSigAppointmentDTO faceSigAppointment = faceSigAppointmentService.selectByPrimaryKey(new Long(dto.getId()).intValue());
			McamLoanApplyInfoDTO acLoanApplyInfo = taskProcessMapper.selectLoanApplyInfo(faceSigAppointment.getLoanId());
			if (acLoanApplyInfo == null) {
				throw new MarvelsBusinessException("loanId为" + faceSigAppointment.getLoanId() + "没有对应的贷款单号");
			}
			FaceSigAppointmentDTO faceSigAppointment_update = new FaceSigAppointmentDTO();
			faceSigAppointment_update.setId(new Long(dto.getId()).intValue());
			faceSigAppointment_update.setFaceSigStatus(FacesigOperationType.IS_FACE_TO_FACE_SIGN);// 状态修改为正在面签
			jsonResult = faceSigAppointmentService.updateAppointment(faceSigAppointment_update,true)+"";
		} catch (Exception e) {
			throw new MarvelsBusinessException("开始面签操作失败!",e);
		}
		return jsonResult;
	}


	public List<Map<String,Object>> getFaceSigTimeConfByDate(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		MarvelsLogUtil.getInstance().info("getFaceSigTimeConfByDate====>>paramMap=" + faceSignApiDto);
		Long timestamp = faceSignApiDto.getTimestamp();
		List<Map<String,Object>> jsonResult = new ArrayList<Map<String,Object>>();
		// 获得历史版本ID
		try {
			 Page<FaceSigConfigurationDTO> faceSigTimeConfList = faceSigConfigurationService.selectStartTime();
			 if(faceSigTimeConfList==null||CollectionUtils.isEmpty(faceSigTimeConfList.getResult())){
				 return null;
			 }
			 //分组完成后，根据分组获取可以面签的人员
			 List<SysUserDTO> userList = faceSigAppointmentService.selectFaceSignUsers();
			 Integer faceJobCount = userList.size();
			 String canAdjustStr = ServerProperties.getValue(filePath, "resource.properties", "facesign.adjust.count");
			 Integer canAdjustNumber  = 0;
			 if(!StringUtils.isEmpty(canAdjustStr)){
				canAdjustNumber = Integer.parseInt(canAdjustStr);
			 }
			 MarvelsLogUtil.getInstance().info("freeCount==>>调整数:"+canAdjustNumber);
			 for (FaceSigConfigurationDTO faceSigTimeConf : faceSigTimeConfList) {
				 //已预约的人数
				 FaceSigAppointmentDTO dto = new FaceSigAppointmentDTO();
				 dto.setTimeId(faceSigTimeConf.getFacesigId());
				 dto.setAppointmentDate(new Date(timestamp));
				 Integer count = faceSigAppointmentService.queryDateTimeCount(dto);
				 Map<String,Object> paramMap = new HashMap<String,Object>();
				 paramMap.put("id", faceSigTimeConf.getFacesigId());
				 paramMap.put("starttime", faceSigTimeConf.getStartTime().getTime());
				 paramMap.put("endtime", faceSigTimeConf.getEndTime().getTime());
				 paramMap.put("freeCount", faceJobCount-canAdjustNumber-count);
				 paramMap.put("timeConfHistoryId", faceSigTimeConf.getTimeConfHistoryId());
				 jsonResult.add(paramMap);
			 }
			 MarvelsLogUtil.getInstance().info("获取时间列表返回参数：===============》"+faceSigTimeConfList);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("获取时间列表异常=====>>>>"+e);
			throw new MarvelsBusinessException("获取失败！",e);
		}
		return jsonResult;
	}

	/**
	 * 未预约
	 */
	public Map<String,Object> queryLoanList(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		MarvelsLogUtil.getInstance().info("queryLoanList>>>>>>>>>>>>paramMap==>>" + faceSignApiDto);
		Integer id = faceSignApiDto.getUserId();
		if(id==null) throw new MarvelsBusinessException("用户id为空");
		Integer pageNo = faceSignApiDto.getPageNo();
		Integer pageSize = faceSignApiDto.getPageSize();
		McamLoanApplyInfoDTO dto = new McamLoanApplyInfoDTO();
		dto.setEmployeeId(String.valueOf(id));
		dto.setStatus(LoanStateConstant.P01);
		if(null == pageNo || pageNo < 1){
			pageNo=PageConstant.CURRPAGE;
		}
		if(null == pageSize || pageSize < 1){
			pageSize=20;
		}
		PageHelper.startPage(pageNo, pageSize);
		List<McamLoanApplyInfoDTO> loanInfos = taskProcessMapper.queryLoanApplyInfo(dto);
		if(CollectionUtils.isEmpty(loanInfos)){
			return PageConverter.converter(new PageInfo<Map<String,Object>>(new ArrayList<Map<String,Object>>()));
		}
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		for (McamLoanApplyInfoDTO mcamLoanApplyInfoDTO : loanInfos) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", mcamLoanApplyInfoDTO.getId());
			map.put("custIdCard", mcamLoanApplyInfoDTO.getCustCardNo());
			map.put("apply_time", mcamLoanApplyInfoDTO.getApplyTime()==null?0:mcamLoanApplyInfoDTO.getApplyTime().getTime());
			map.put("applyTime", mcamLoanApplyInfoDTO.getApplyTime()==null?0:mcamLoanApplyInfoDTO.getApplyTime().getTime());
			map.put("status", mcamLoanApplyInfoDTO.getStatus());
			map.put("mobileNum", mcamLoanApplyInfoDTO.getMobileNo());
			map.put("userId", mcamLoanApplyInfoDTO.getEmployeeId());
			map.put("custName", mcamLoanApplyInfoDTO.getCustName());
			map.put("productName", mcamLoanApplyInfoDTO.getProductName());
			map.put("loanId", mcamLoanApplyInfoDTO.getLoanId());
			map.put("referrerMobileNum", "");
			map.put("productId", mcamLoanApplyInfoDTO.getProductCode());
			list.add(map);
		}
		PageInfo<Map<String,Object>> pageInfo = new PageInfo<Map<String,Object>>(list);
		MarvelsLogUtil.getInstance().info("获取未预约列表返回参数：===============》"+pageInfo);
		return PageConverter.converter(pageInfo);
	}
	/**
	 * 获取已预约列表
	 */
	public Map<String, Object> appointmentByAppointmentList(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info("appointmentByAppointmentList>>>>>>>>>>>>faceSignApiDto==>>" + faceSignApiDto);
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		String userType= faceSignApiDto.getUserType();//用户类型
		Integer id= faceSignApiDto.getUserId();//用户ID
		if(id==null) throw new MarvelsBusinessException("用户ID为空");
		Integer faceSigStatus = faceSignApiDto.getFaceSigStatus();//面签状态
		String isallot = faceSignApiDto.getIsallot();//是否分配
		Integer pageNo = faceSignApiDto.getPageNo();
		Integer pageSize = faceSignApiDto.getPageSize();
		Map<String, Object> page = new HashMap<String,Object>();
		try {
			FaceSigAppointmentDTO faceSigAppointmentDto = new FaceSigAppointmentDTO();
			if ("3".equals(userType)) {// 如果是助理
				faceSigAppointmentDto.setAssistantId(id);
			} else {
				faceSigAppointmentDto.setUserId(id);
			}
			faceSigAppointmentDto.setCancel(1);
			faceSigAppointmentDto.setIsDelete(1);
			if (faceSigStatus != null) {
				if (faceSigStatus == 3) {// 已过号
					faceSigAppointmentDto.setFaceSigStatus(FacesigOperationType.HAS_PASSED);
				} else if (faceSigStatus == 0) {
					faceSigAppointmentDto.setUnFaceSig("Y");//未面签和正在面签
				}
			}
			if ("y".equalsIgnoreCase(isallot)) {// 如果已分配
				faceSigAppointmentDto.setAllot(1);
			} else if ("n".equalsIgnoreCase(isallot)) {// 如果未分配
				faceSigAppointmentDto.setAllot(0);
			}
			faceSigAppointmentDto.setOrder("y");
			faceSigAppointmentDto.setCancel(1);
			Page<FaceSigAppointmentDTO> pageList = faceSigAppointmentService.getFaceSigAppointmentPage(faceSigAppointmentDto, pageNo, pageSize);
			
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			for (FaceSigAppointmentDTO faceSigAppointment : pageList) {
				list.add(assembleParam(faceSigAppointment));
			}
			if(CollectionUtils.isEmpty(list)){
				page.put("list", new ArrayList<Map<String,Object>>());
				page.put("count", 0);
			}else{
				page.put("list", list);
				page.put("count", list.size());
			}
			 MarvelsLogUtil.getInstance().info("查询已预约列表返回参数：===============》"+page);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("appointmentByAppointmentList_ex", e);
			throw new MarvelsBusinessException("查询已预约列表失败");
		}
		return page;
	}
	/**
	 * 组装参数
	 * @param faceSigAppointment
	 * @param page
	 * @throws MarvelsBusinessException
	 */
	private Map<String,Object> assembleParam(FaceSigAppointmentDTO faceSigAppointment) throws MarvelsBusinessException{
		String loanId = faceSigAppointment.getLoanId();
		McamLoanApplyInfoDTO acLoanApplyInfo = taskProcessMapper.selectLoanApplyInfo(loanId);
		if (acLoanApplyInfo == null) {
			throw new MarvelsBusinessException("loanId为" + loanId + "没有对应的贷款单号");
		}
		Map<String, Object> loanApplyInfoMap = new HashMap<String, Object>();
		List<RoomLogDTO> roomLogList = roomLogMapper.selectRoomLogList(new Long(faceSigAppointment.getId()).intValue());// 查询是否进入过房间
		if (CollectionUtils.isEmpty(roomLogList)) {
			loanApplyInfoMap.put("isEnterRoom", 0);
		} else {
			loanApplyInfoMap.put("isEnterRoom", roomLogList.size());
		}
		loanApplyInfoMap.put("currentTime", new Date().getTime());
		loanApplyInfoMap.put("appointmentId", faceSigAppointment.getId());
		loanApplyInfoMap.put("roomId", faceSigAppointment.getRoomId());

		loanApplyInfoMap.put("userId", acLoanApplyInfo.getEmployeeId());
		loanApplyInfoMap.put("loanId", acLoanApplyInfo.getLoanId());
		loanApplyInfoMap.put("mobileNum", acLoanApplyInfo.getMobileNo());
		loanApplyInfoMap.put("productId", acLoanApplyInfo.getProductType());
		loanApplyInfoMap.put("productName", acLoanApplyInfo.getProductName());
		loanApplyInfoMap.put("custName", acLoanApplyInfo.getCustName());
		loanApplyInfoMap.put("custIdCard", acLoanApplyInfo.getCustCardNo());// 身份证号码
		Date apponitmentCreateTime = faceSigAppointment.getAppointmentDate();// 预约日期
		loanApplyInfoMap.put("appointmentDate", DateUtils.getDateYYYY_MM_DD(apponitmentCreateTime));
		FaceSigConfigurationDTO faceSigTimeConf = faceSigConfigurationService.selectByPrimaryKey(faceSigAppointment.getTimeId());
		loanApplyInfoMap.put("appointmentTimeStartTime", DateUtils.getDateHHMM(faceSigTimeConf.getStartTime()));
		loanApplyInfoMap.put("appointmentTimeEndTime", DateUtils.getDateHHMM(faceSigTimeConf.getEndTime()));
		loanApplyInfoMap.put("createTime", faceSigAppointment.getCreateTime());
		loanApplyInfoMap.put("faceSigStatus", faceSigAppointment.getFaceSigStatus());
		loanApplyInfoMap.put("assistantId", faceSigAppointment.getAssistantId());
		if (faceSigAppointment.getAssistantId() != null) {
			ChannelUserDTO user = consumerUmApi.queryUserById(faceSigAppointment.getAssistantId());
			loanApplyInfoMap.put("assistantName", user.getRealName());
			loanApplyInfoMap.put("assistantMobileNo", user.getMobileNo());
			ChannelUserDTO managerUser = consumerUmApi.queryUserById(faceSigAppointment.getUserId());
			loanApplyInfoMap.put("managerMobileNo", managerUser.getMobileNo()); // 客户经理电话号码
			loanApplyInfoMap.put("managerName", managerUser.getRealName()); // 客户经理姓名

		}
		return loanApplyInfoMap;
	}
	/**
	 * 分配助理
	 * 
	 * @param assistantDto
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public String allotAssistant(AssistantDTO assistantDto) throws MarvelsBusinessException {
		if(assistantDto==null) throw new MarvelsBusinessException("入参为空");
		 MarvelsLogUtil.getInstance().info("allotAssistant===>>"+JSONObject.fromObject(assistantDto));
		 if(assistantDto.getAssistantId()==null){
			 throw new MarvelsBusinessException("缺少助理ID!");
		 }
		 ChannelUserDTO assistantUser= consumerUmApi.queryUserById(assistantDto.getAssistantId());
		 if(assistantUser==null||!"3".equals(assistantUser.getUserType())){
			 throw new MarvelsBusinessException("没有该助理!");
		 }
		 Integer appointmentId= assistantDto.getAppointmentId();
		
		 FaceSigAppointmentDTO faceSigAppointment =faceSigAppointmentService.selectByPrimaryKey(appointmentId);
		 if(faceSigAppointment==null){
			 throw new MarvelsBusinessException("没有该预约!");
		 }
		Integer result=0;
		try {
			FaceSigAppointmentDTO faceSigAppointmentParam = new FaceSigAppointmentDTO();
			 faceSigAppointmentParam.setId(appointmentId);
			 faceSigAppointmentParam.setAssistantId(assistantUser.getId());
			 faceSigAppointmentParam.setcId(assistantUser.getCid());
			result = faceSigAppointmentService.updateAppointment(faceSigAppointmentParam,false);
		} catch (Exception e) {
			throw new MarvelsBusinessException("分配失败!",e);
		}
		return result.toString();
	}

	/**
	 * 获得客户经理对应的助理
	 * 
	 * @param token
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public Map<String,Object> getAssistant(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		Integer pageNo = faceSignApiDto.getPageNo();
		Integer pageSize = faceSignApiDto.getPageSize();
		Integer id = faceSignApiDto.getUserId();
		if (pageNo == null || pageSize == null) {
			throw new MarvelsBusinessException("缺少分页信息!");
		}
		if (id == null) {
			throw new MarvelsBusinessException("用户ID为空!");
		}

		Map<String,Object> result = new HashMap<String,Object>();
		try {
			List<ChannelUserDTO> page = consumerUmApi.queryByClientManagerId(id, (pageNo-1)/pageSize, pageSize);
			if(CollectionUtils.isEmpty(page)){
				result.put("list", new ArrayList<Map<String,Object>>());
				result.put("count", 0);
			}else{
				result.put("list", page);
				result.put("count", page.size());
			}
			MarvelsLogUtil.getInstance().info("获取客户经理对应的助理返回参数：===============》"+result);
		} catch (Exception e) {
			throw new MarvelsBusinessException("获取客户经理对应的助理失败!",e);
		}
		return result;
	}

	/**
	 * 取消分配
	 * 
	 * @param token
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public String cancelAllot(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		Integer appointmentId = faceSignApiDto.getAppointmentid();
		Integer id = faceSignApiDto.getUserId();
		if(id==null||id==0){
			throw new MarvelsBusinessException("用户ID为空");
		}
		if (appointmentId == null) {
			throw new MarvelsBusinessException("预约ID为空");
		}
		FaceSigAppointmentDTO faceSigAppointment = faceSigAppointmentService.selectByPrimaryKey(appointmentId);
		if (faceSigAppointment == null) {
			throw new MarvelsBusinessException("无该预约信息!");
		}

		if (!id.equals(faceSigAppointment.getUserId())) {
			throw new MarvelsBusinessException("非法操作!");
		}
		faceSigAppointment.setId(faceSigAppointment.getId());
		faceSigAppointment.setAssistantId(null);
		Integer result=0;
		try {
			faceSigAppointmentDao.cancelAllot(faceSigAppointment.getAssistantId(), faceSigAppointment.getId());
		} catch (Exception e) {
			throw new MarvelsBusinessException("取消失败!",e);
		}
		return result.toString();
	}
    /***
     * 房间记录
     */
    @Transactional(timeout = 30 ,rollbackFor = Exception.class)
	@Override
	public Integer insertRoomLog(RoomLogDTO roomLogDTO) throws MarvelsBusinessException {
    	MarvelsLogUtil.getInstance().info("========================生成房间记录日志insertRoomLog,入参："+roomLogDTO);
    	if(roomLogDTO==null) throw new MarvelsBusinessException("入参为空");
    	RoomLogDTO roomLog = new RoomLogDTO();
    	roomLog.setAppointmentId(roomLogDTO.getAppointmentId());
		roomLog.setLoanId(roomLogDTO.getLoanId());
		roomLog.setEnterRoomNo(roomLogDTO.getEnterRoomNo());
		roomLog.setEnterRoomTime(roomLogDTO.getEnterRoomTime());
		roomLog.setUserId(roomLogDTO.getUserId());
		roomLog.setUserType(roomLogDTO.getUserType());
		return roomLogMapper.insertRoomLog(roomLogDTO);
	}

	@Override
	public Integer modifyAppointMentStatus(FaceSigAppointmentDTO faceSigAppointmentDTO) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info("开始更新面签状态=======》"+faceSigAppointmentDTO);
		if(faceSigAppointmentDTO==null) throw new MarvelsBusinessException("入参为空");
		Integer count = faceSigAppointmentService.updateAppointment(faceSigAppointmentDTO,false);
		MarvelsLogUtil.getInstance().info("更新面签状态结束=======》"+faceSigAppointmentDTO);
		return count;
	}
	/**
	 * 坐席获得签名以及相关登录信息
	 * 
	 * @param faceJobId
	 * @return
	 * @throws MarvelsBusinessException 
	 */

	public Map<String, Object> getTencentSigByFaceJobId(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		String faceJobId = faceSignApiDto.getFaceJobId();
		MarvelsLogUtil.getInstance().info("getTencentSigByFaceJobId入参  faceSignApiDto===>>" + faceSignApiDto);
		if (StringUtils.isEmpty(faceJobId)) {
			throw new MarvelsBusinessException("userId为空");
		}

		String sig = null;//QCloudSigUtils.createSig(faceJobId,filePath);
		boolean sigVerify = false;//QCloudSigUtils.checkSig(sig, faceJobId,filePath);
		MarvelsLogUtil.getInstance().info("签名结果=sig result>>" + sigVerify);
		if (sigVerify == false) {
			throw new MarvelsBusinessException("签名失败!");
		}

		Map<String, Object> loginInfoMap = new HashMap<String, Object>();
		loginInfoMap.put("sdkAppID", TencentCloud.SDKAPPID);
		loginInfoMap.put("appIDAt3rd", TencentCloud.SDKAPPID);
		loginInfoMap.put("identifier", faceJobId);
		loginInfoMap.put("userSig", sig);
		loginInfoMap.put("accountType", TencentCloud.ACCOUNTTYPE);
		MarvelsLogUtil.getInstance().info("getTencentSigByFaceJobId坐席获得签名以及相关登录信息返回值========》》》》》："+loginInfoMap);
		return loginInfoMap;
	}
	/**
	 * 获取坐席正在面签的的预约和助理获取
	 * 
	 * @param faceJobId
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public Map<String, Object> queryFaceSiging(FaceSignApiDTO faceSignApiDto)throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		MarvelsLogUtil.getInstance().info("queryFaceSiging入参==>>faceSignApiDto:" + faceSignApiDto.toString());
		String faceJobId = faceSignApiDto.getFaceJobId();
		Integer pageNo = faceSignApiDto.getPageNo();
		Integer pageSize = faceSignApiDto.getPageSize();
		if (StringUtils.isEmpty(faceJobId)) {
			throw new MarvelsBusinessException("无坐席ID");
		}
		FaceSigAppointmentDTO faceSigAppointment = new FaceSigAppointmentDTO();
		faceSigAppointment.setFaceSigStatus("1");
		faceSigAppointment.setFaceJobId(faceJobId);
		faceSigAppointment.setCancel(1);
		if (pageNo==null||pageNo <= 0) {
			pageNo = PageConstant.CURRPAGE;
		}
		if (pageSize==null||pageSize <= 0) {
			pageSize =10;
		}
		Page<FaceSigAppointmentDTO> listFaceSigAppointment = faceSigAppointmentService.getFaceSigAppointmentPage(faceSigAppointment, pageNo, pageSize);
		if (listFaceSigAppointment != null && listFaceSigAppointment.size() > 1) {
			throw new MarvelsBusinessException("数据有误!");
		}
		if (CollectionUtils.isEmpty(listFaceSigAppointment)) {
			throw new MarvelsBusinessException("无数据!");
		}
		Map<String, Object> item = new HashMap<String, Object>();
		FaceSigConfigurationDTO faceSigTimeConf = faceSigConfigurationService.selectByPrimaryKey(new Long(listFaceSigAppointment.get(0).getTimeId()).intValue());
		item.put("startTime", DateUtils.getDateHHMM(faceSigTimeConf.getStartTime()));
		item.put("timeSlot", DateUtils.getDateHHMM(faceSigTimeConf.getStartTime()) + "-" + DateUtils.getDateHHMM(faceSigTimeConf.getEndTime()));
		ChannelUserDTO user = consumerUmApi.queryUserById(listFaceSigAppointment.get(0).getUserId());
		item.put("userName", user.getRealName());
		item.put("appointmentDate", DateUtils.getDateYYYY_MM_DD(listFaceSigAppointment.get(0).getAppointmentDate()));
		item.put("loanId", listFaceSigAppointment.get(0).getLoanId());
		item.put("faceSigStatus", Integer.parseInt(listFaceSigAppointment.get(0).getFaceSigStatus()));
		item.put("faceJobId", listFaceSigAppointment.get(0).getFaceJobId());
		item.put("createTime", listFaceSigAppointment.get(0).getCreateTime());
		McamLoanApplyInfoDTO acLoanApplyInfo = taskProcessMapper.selectLoanApplyInfo(listFaceSigAppointment.get(0).getLoanId());
		if (acLoanApplyInfo != null) {
			item.put("custName", acLoanApplyInfo.getCustName());
			item.put("mobileNum", acLoanApplyInfo.getMobileNo());
		}
		MarvelsLogUtil.getInstance().info("queryFaceSiging返回参数=======》》》》》:" + faceSignApiDto.toString());
		return item;
	}
	/**
	 * 登录
	 */
	@Override
	public String faceJobLogin(UserDTO user, HttpServletRequest request) throws MarvelsBusinessException {
		if(user==null) throw new MarvelsBusinessException("入参为空");
		MarvelsLogUtil.getInstance().info("面签APP登录入参=======》》》》》："+user.toString());
		MarvelsResultDTO  resultDto = consumerSystemApi.login(user, request);
		if(resultDto==null||!MarvelsErrorCode.SUCCESS.getValue().equals(resultDto.getCode())){
			throw new MarvelsBusinessException("登录失败");
		}
		return user.getUserCode();
	}
	/**
	 * 前端预览合同
	 */
	@Override
	public String html(FaceSignApiDTO faceSignApiDto) throws MarvelsBusinessException {
		if(faceSignApiDto==null) throw new MarvelsBusinessException("入参为空");
		MarvelsLogUtil.getInstance().info("html前端预览合同入参=======》》》》》:" + faceSignApiDto.toString());
		Map<String,Object> htmlMap = faceCheckAssignmentService.previewLoanCompact(faceSignApiDto.getLoanId(), faceSignApiDto.getTemplateType());
		MarvelsLogUtil.getInstance().info("html前端预览合同获取的合同信息=======》》》》》:" + htmlMap);
		String html = null;
		if(htmlMap!=null){
			html = (String) htmlMap.get("htmlData");
			MarvelsLogUtil.getInstance().info("html前端预览合同获取的合同HTML=======》》》》》:" + html);
			if(!StringUtils.isEmpty(html)){
				return html;
			}
		}
		return "无协议信息";
	}
	@Override
	public List<RoomLogDTO> selectRoomLogList(Integer appointmentId) throws MarvelsBusinessException {
		if(appointmentId == null || appointmentId == 0){
			throw new MarvelsBusinessException("预约号为空");
		}
		List<RoomLogDTO> list = roomLogMapper.selectRoomLogList(appointmentId);
		return list;
	}

}
